<?php
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2016/9/18
 * Time: 11:52
 */

namespace app\manage\controller;
class Nav extends Base
{
    //前置操作定义
    protected $beforeActionList = [
        'beforeIndex' =>  ['only'=>'index'],
        'beforeEdit'  => ['only'=>'edit'],
    ];
    public function _initialize(){
        parent::_initialize();
    }
    public function beforeIndex(){
        $this->sort = 'ordid';
        $this->order = 'asc,id desc';
        $big_menu = [
            'title' => '添加导航',
            'iframe' => url('add'),
            'id' => 'add',
            'width' => '500',
            'height' => '360'
        ];
        $this->_exclude = 'delete';
        $this->_ajaxedit = true;
        $this->assign('big_menu', $big_menu);
    }
    public function beforeEdit(){
        $id      = input('param.id/d',0);
        $spid    = 0;
        if($id){
            $cate_id = model('nav')->where(['id'=>$id])->value('cate_id');
            $detail  = model('one_cate')->where(['status'=>1,'id'=>$cate_id])->field('id,spid')->find();
            $spid    = !empty($detail['spid'])?$detail['spid'].$detail['id']:$detail['id'];
        }

        $this->assign('spid',$spid);
    }
    public function addDo(){
        \app\common\model\Nav::event('after_insert',function($obj){
            $this->doCache();
        });
        parent::addDo();
    }
    public function editDo(){
        \app\common\model\Nav::event('after_update',function($obj){
            $this->doCache();
        });
        parent::editDo();
    }
    public function delete(){
        \app\common\model\Nav::event('after_delete',function($obj){
            $this->doCache();
        });
        parent::delete();
    }
    /**
     * 更新导航缓存
     */
    public function cache(){
        if($this->doCache()){
            $this->success('导航缓存更新成功');
        }else{
            $this->error('导航缓存更新失败');
        }
    }
    public function doCache(){
        $lists = model('nav')->where('status',1)->order('ordid asc')->select();
        if($lists){
            $cate = objToArray($lists);//普通列表
            $temp = [];
            foreach($cate as &$v){
                if(!empty($v['alias'])){
                    $temp[$v['alias']] = $v;
                }else{
                    $temp[$v['model']] = $v;
                }
            }
            cache('nav',$temp);
            return true;
        }
        return false;

    }
}